<!-- 子组件 VideoPlayer.vue -->
<script setup>
import { watch, ref, nextTick, onMounted, onBeforeUnmount, reactive, computed } from 'vue'
import {throttle} from 'loadsh'

const props = defineProps({
  stream: MediaStream,
  rotation: Number
})

const emits = defineEmits(['oprcallback','degChanged', 'getScreenRate'])

const LONG_PRESS_DURATION = 500 // ms
const BUFFER_DELAY = 10        // ms

const videoRef = ref(null)

const longSide = ref(null)
const shortSide = ref(null)
const direction = ref(0)

const screenStyle = ref({
  width: 240,
  height: 550,
})          // 控制容器样式

const videoStyle = ref({
  width: '100%',
  height: 'auto'
})

const wrapperRef = ref()

const keyPressStartTime = {}
let keyInputBuffer = ''
let keyBufferTimer = null

const isLongPress = ref(false)
const isPressSlide = ref(false)
const startPoint = ref({ x: 0, y: 0 })
const currentPoint = ref({ x: 0, y: 0 })
const longPressTimer = ref(null)

const analyseShortcutKey = (ctrlPressed, pressedKey) => {
    let order = ''
    if (ctrlPressed){
        switch (pressedKey){
            case 'h':
                // console.log("ctrl h")
                order = 'keyboard/home'
                break
            case 'o':
                // console.log("ctrl o")
                order = 'keyboard/recent'
                break
            case 'b':
                // console.log("ctrl b")
                order = 'keyboard/back'
                break
            case 'c':
                // console.log("ctrl c")
                order = 'keyboard/copy'
                break
            case 'v':
                // console.log("ctrl v")
                order = 'keyboard/paste'
                break
            default:
                return
        }
    } else {
      order = 'keyword/enter'
    }
    if (order) {
        emits('oprcallback',order)
    }
}
const handleKeyDown = (e) => {
  const key = e.key.toLowerCase()

  // 阻止默认行为（如 Ctrl+S、F5 等）
  if ((e.ctrlKey && ['c', 'v', 'h', 'o', 'b'].includes(key)) || key === 'Enter') {
    e.preventDefault()
    analyseShortcutKey(e.ctrlKey, key)
    return
  }

  // 输入缓冲记录
  keyInputBuffer += key
  if (keyBufferTimer) clearTimeout(keyBufferTimer)
  keyBufferTimer = setTimeout(() => {
    // console.log(`100ms内输入内容：${keyInputBuffer}`)
    // 这里处理输入的内容（如：快捷词判断）
    emits('oprcallback',`keyboard/write?key=${keyInputBuffer[0]}`)
    keyInputBuffer = ''
  }, BUFFER_DELAY)
}

const handleKeyUp = (e) => {
  const key = e.key.toLowerCase()
  delete keyPressStartTime[key]
}

const ratePositionComputed = (e) => {
  const shortRate = (shortSide.value/longSide.value)
  if ([0,1].includes(props.rotation)){
    const nowx = e.x
    const nowy = e.y
    const cmpdWidth = Math.floor(shortSide.value/(shortRate*550)*nowx)
    const cmpdHeight = Math.floor(longSide.value/550*nowy)
    return {x:cmpdWidth, y:cmpdHeight}
  } 
    const nowx = 550 - e.x
    const nowy = (shortRate*550) - e.y
    const cmpdHeight = Math.floor(shortSide.value/(shortRate*550)*nowy)
    const cmpdWidth = Math.floor(longSide.value/550*nowx)
    return {x:cmpdWidth, y:cmpdHeight}
}
let occurMouse = false
let moveCount = 0
const isDistanceEnough = (start, end, threshold = 5) => {
  const dx = end.x - start.x
  const dy = end.y - start.y
  return Math.sqrt(dx * dx + dy * dy) > threshold
}

// 触发两次才算是触发了长触摸事件
const handleMouseDown = (e) => {
  const div = wrapperRef.value
  if (!div) return
  occurMouse = true
  const rect = div.getBoundingClientRect()
  if (
    e.clientX < rect.left ||
    e.clientX > rect.right ||
    e.clientY < rect.top ||
    e.clientY > rect.bottom
  ) {
    // 鼠标移出了 wrapper 区域
    // 可以阻止操作或模拟锁定
    // console.log('鼠标已移出区域')
    return
    // 可选做法：设置鼠标样式或忽略拖拽逻辑等
  } 
  const x = e.clientX - rect.left
  const y = e.clientY - rect.top
  startPoint.value = { x, y }
  currentPoint.value = { ...startPoint.value }

  // 启动长按定时器（比如 500ms）
  longPressTimer.value = setTimeout(() => {
    if (startPoint.value.x === currentPoint.value.x && startPoint.value.y === currentPoint.value.y){
      isLongPress.value = true
      // console.log('长按触发')
      const dt = ratePositionComputed(currentPoint.value)
      emits('oprcallback', `mouse/press?x=${dt.x}&y=${dt.y}`)
    }
    // 可以触发自定义长按事件
  }, 500)

}
// 能进这里的就不是滑动事件
const handleMouseMove = throttle((e) => {
  if (!occurMouse) return
  if (moveCount < 3) {
    moveCount+=1
    // 如果移动次数超过10次，认为是滑动事件
    return
  }
  const div = wrapperRef.value
  if (!div) return

  const rect = div.getBoundingClientRect()
  const x = e.clientX - rect.left
  const y = e.clientY - rect.top
  currentPoint.value = { x, y }
  if (isLongPress.value === true || startPoint.value.x <= 0) {
    return
  }
  if (
    e.clientX < rect.left ||
    e.clientX > rect.right ||
    e.clientY < rect.top ||
    e.clientY > rect.bottom
  ) {
    // 鼠标移出了 wrapper 区域
    // 可以阻止操作或模拟锁定
    // console.log('鼠标已移出区域')
    return
    // 可选做法：设置鼠标样式或忽略拖拽逻辑等
  } 
  if (isPressSlide.value === false){
    clearInterval(longPressTimer.value)
    isPressSlide.value = true
    // console.log("手机触摸按下事件")
    const dt = ratePositionComputed(currentPoint.value)
    emits('oprcallback', `mouse/down?x=${dt.x}&y=${dt.y}`)
    return
  }

  const dt1 = ratePositionComputed(currentPoint.value)
  emits('oprcallback', `mouse/move?x=${dt1.x}&y=${dt1.y}`)
  // console.log('鼠标移动:', currentPoint.value)
}, 100)  // 每 50ms 执行一次

const handleMouseUp = (e) => {
  const tempMoveCount = moveCount
  moveCount = 0
  if (!occurMouse) return
  occurMouse = false
  const div = wrapperRef.value
  if (!div) return
  const rect = div.getBoundingClientRect()
  let x
  let y
  if (
    e.clientX < rect.left ||
    e.clientX > rect.right ||
    e.clientY < rect.top ||
    e.clientY > rect.bottom
  ) {
    // 鼠标移出了 wrapper 区域
    // console.log('鼠标已移出区域')
    if (e.clientX < rect.left) {
      x = 0
    } else if (e.clientX > rect.right) {
      x = rect.width
    } else {
      x = e.clientX - rect.left
    }

    if (e.clientY < rect.top) {
      y = 0
    } else if (e.clientY > rect.bottom) {
      y = rect.height
    } else {
      y = e.clientY - rect.top
    }

  } else {
    // 鼠标在区域内，正常计算坐标
    x = e.clientX - rect.left
    y = e.clientY - rect.top
  }
  currentPoint.value = { x, y }
  if (longPressTimer.value) {
    clearTimeout(longPressTimer.value)
    longPressTimer.value = null
  }
  if (isLongPress.value === true){
    isLongPress.value = false
    emits('oprcallback', `mouse/release`)
  } else if(isPressSlide.value ===true && tempMoveCount >= 4){
    isPressSlide.value = false
      // console.log('鼠标触摸抬起事件', { x, y })
      const dt = ratePositionComputed(currentPoint.value)
      emits('oprcallback', `mouse/up?x=${dt.x}&y=${dt.y}`)
  } else if (isDistanceEnough(startPoint.value, currentPoint.value)) {
  // 判定为滑动
  // console.log('鼠标滑动事件', { x, y })
  const dt = ratePositionComputed(startPoint.value)
  const dt1 = ratePositionComputed(currentPoint.value)
  emits('oprcallback', `mouse/swipe?x=${dt.x}&y=${dt.y}&ex=${dt1.x}&ey=${dt1.y}`)
} else {
  // 点击
  // console.log('鼠标点击事件', { x, y })
  const dt = ratePositionComputed(currentPoint.value)
  emits('oprcallback', `mouse/click?x=${dt.x}&y=${dt.y}`)
}
  startPoint.value = {x:0}
  currentPoint.value = {x:0}
}

const handleGlobalMouseUp = (e) => {
  handleMouseUp(e)  // 复用你原来的 handleMouseUp
}
watch(()=> props.rotation, ()=>{
  if (props.rotation === 0 || props.rotation === 2){
    videoStyle.value = {
      width: 'auto',
      height: '100%'
    }
  }else {
    videoStyle.value = {
      width: '100%',
      height: 'auto'
    }
  }
  const screenRate = longSide.value/shortSide.value
  switch (props.rotation) {
    case 0:{
      screenStyle.value = {
        width: Math.floor(550/screenRate),
        height: 550
      }
      break;
    }
    case 2:{
      screenStyle.value = {
        width: Math.floor(550/screenRate),
        height: 550
      }
      break;
    }
    case 1:{
      screenStyle.value = {
        height: Math.floor(550/screenRate),
        width: 550
      }
      break;
    }
    case 3:{
      screenStyle.value = {
        height: Math.floor(550/screenRate),
        width: 550
      }
      break;
    }
    default:
  }
  const video = videoRef.value
  if (!video) return

  // 暂停播放并断开绑定
  video.pause()
  video.srcObject = null

  // 强制刷新 DOM，延迟重新绑定
  setTimeout(() => {
    video.srcObject = props.stream
    video.play()
  }, 50)  // 时间可以调整为 0~100ms
}, {
  immediate: true
})

const checkVideoResolution = () => {
  const video = videoRef.value
  if (!video) return

  const { videoWidth, videoHeight } = video
  if (videoWidth > videoHeight) {
    direction.value = 90
  }
  else {
    direction.value = 0
  }
  emits('degChanged', videoRef.value.clientWidth > videoRef.value.clientHeight)
}

onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('keyup', handleKeyUp)
})
onMounted(()=>{
  window.addEventListener('keydown', handleKeyDown)
  window.addEventListener('keyup', handleKeyUp)
  videoRef.value.srcObject = props.stream
  videoRef.value.onloadedmetadata = () => {
    const width = videoRef.value.videoWidth
    const height = videoRef.value.videoHeight
    // // console.log('视频原始分辨率哈哈:', width, height)
    longSide.value = width > height?width:height
    shortSide.value = width > height?height:width
    videoRef.value.play()
    emits('getScreenRate', parseFloat(longSide.value/shortSide.value).toFixed(2))
  }
  // // console.log("触发视频传输")
})
</script>

<template>
  <div class="video-container"
  @mousedown="handleMouseDown"
    @mousemove="handleMouseMove"
    @mouseup="handleMouseUp"
  >
    <div
    ref="wrapperRef" 
    class="screen"
    :style="{width: `${screenStyle.width}px`, height: `${screenStyle.height}px`}"
    style="
      background: black;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;">
      <video ref="videoRef" 
        autoplay 
        playsinline 
        muted
        :style="{width: videoStyle.width, height: videoStyle.height,'object-fit': 'contain'}" ></video>
    </div>
  </div>
</template>
<style lang="less" scoped>
.video-container{
  width: 100%;
  height: 100%;
}
.screen{
  width: 245px;
  height: 550px;
  border-radius: 18px;
  position: absolute;
  overflow: hidden;
  top: 50%;
  left: 50%; 
  transform: translate(-50%, -50%);
}
</style>